package com.mpj.yolov12

import android.app.Activity
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.widget.Button
import android.widget.FrameLayout
import android.widget.TextView

class SecActivity : Activity(), OnUIProcessListener {
    private val TAG = "SecActivity"

    private lateinit var imageView: BitmapSurfaceView
    private lateinit var parentLayout: FrameLayout
    private lateinit var statusText: TextView
    private lateinit var startListenerBtn: Button
    private lateinit var stopListenerBtn: Button
    private lateinit var backButton: Button

    private val mainHandler = Handler(Looper.getMainLooper())

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // 设置布局
        setContentView(R.layout.activity_sec)
        // 初始化 DataStreamProcessHelper
        DataStreamProcessHelper.instance.init(this)
        // 创建UDP监听器(默认端口8888)
        DataStreamProcessHelper.instance.setUIProcessListener(this)
        // 获取显示图像的SurfaceView
        imageView = DataStreamProcessHelper.instance.getImageView()

        parentLayout = findViewById<FrameLayout>(R.id.parent_layout)
        parentLayout.addView(imageView)
        // 初始化图像 必须在添加布局之后初始化图片数据因为涉及到宽高的重置等
        DataStreamProcessHelper.instance.initImage(this)

        statusText = findViewById(R.id.statusText)
        startListenerBtn = findViewById(R.id.startListener)
        stopListenerBtn = findViewById(R.id.stopListener)
        backButton = findViewById(R.id.backButton)


        // 设置按钮点击事件
        startListenerBtn.setOnClickListener {
            DataStreamProcessHelper.instance.startUdpBroadcastListening()
        }

        stopListenerBtn.setOnClickListener {
            DataStreamProcessHelper.instance.stopUdpBroadcastListening()
        }

        backButton.setOnClickListener {
            DataStreamProcessHelper.instance.stopUdpBroadcastListening()
            finish() // 返回上一页
        }
        updateReceivedDataStatus("准备就绪", false)
    }


    override fun onResume() {
        super.onResume()
        DataStreamProcessHelper.instance.openWifiManager(this)
    }

    override fun onPause() {
        super.onPause()
        DataStreamProcessHelper.instance.releaseWifiManager()
    }

    override fun onDestroy() {
        super.onDestroy()
        DataStreamProcessHelper.instance.stopUdpBroadcastListening()
    }


    override fun onUDPInfoReceived(udpInfo: UDPInfo) {
        updateReceivedDataStatus("已收到数据", false)
    }

    override fun updateReceivedDataStatus(status: String, isListening: Boolean) {
        mainHandler.post {
            statusText.text = status
        }
    }
}
